import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/animation.dart';

import 'action.dart';
import 'state.dart';

Reducer<HomeworkPostState> buildReducer() {
  return asReducer(
    <Object, Reducer<HomeworkPostState>>{
      HomeworkPostAction.next: _next,
      HomeworkPostAction.selectClass: _selectClass,
      HomeworkPostAction.selectType: _selectType,
      HomeworkPostAction.edit: _edit,
      HomeworkPostAction.startTime: _startTime,
      HomeworkPostAction.endTime: _endTime,
      HomeworkPostAction.value: _value,
    },
  );
}

HomeworkPostState _next(HomeworkPostState state, Action action) {
  final HomeworkPostState newState = state.clone();
  newState.controller
      .nextPage(duration: Duration(milliseconds: 300), curve: Curves.linear);
  return newState;
}

HomeworkPostState _selectClass(HomeworkPostState state, Action action) {
  final HomeworkPostState newState = state.clone();
  String classId = action.payload;
  if (newState.selectClasses.contains(classId)) {
    newState.selectClasses.remove(classId);
  } else {
    newState.selectClasses.add(classId);
  }
  return newState;
}

HomeworkPostState _selectType(HomeworkPostState state, Action action) {
  return state.clone()..type = action.payload;
}

HomeworkPostState _edit(HomeworkPostState state, Action action) {
  var newState = state.clone();

  Map<String, String> values = action.payload;
  values.forEach((key, value) {
    switch (key) {
      case 'title':
        newState.title = value;
        break;
      case 'demand':
        newState.demand = value;
        break;
      case 'ideation':
        newState.ideation = value;
        break;
      case 'keywords':
      default:
        newState.keywords = value;
        break;
    }
  });

  return newState;
}

HomeworkPostState _startTime(HomeworkPostState state, Action action) {
  return state.clone()..start = action.payload;
}

HomeworkPostState _endTime(HomeworkPostState state, Action action) {
  return state.clone()..end = action.payload;
}

HomeworkPostState _value(HomeworkPostState state, Action action) {
  var newState = state.clone();
  action.payload.forEach((key, value) {
    switch (key) {
      case 'minCount':
        newState.minCount = value;
        break;
      case 'maxCount':
        newState.maxCount = value;
        break;
      case 'minScore':
        newState.minScore = value;
        break;
      case 'maxScore':
        newState.maxScore = value;
        break;
      case 'passScore':
        newState.passScore = value;
        break;
    }
  });
  return newState;
}
